﻿#include "logprintmgr.h"
#include "logconslprinter.hpp"
#include "logcustprinter.hpp"
#include "logfileprinter.h"

NAMESPACE_USE
LoggerPrintMgr::LoggerPrintMgr() {
    std::thread(std::bind(&LoggerPrintMgr::_run, this)).detach();
}

LoggerPrintMgr::~LoggerPrintMgr() {

}

void LoggerPrintMgr::_run() {
    while (1) {
        LogItem item;
        {
            std::unique_lock<std::mutex> lock(mtx_);
            if (logger_que_.empty())
            {
                cv_.wait(lock, [&]() {
                    if (logger_que_.empty())
                        return false;
                    item = logger_que_.front();
                    logger_que_.pop_front();
                    return true;
                });
            }
            else {
                item = logger_que_.front();
                logger_que_.pop_front();
            }

        }

        if (log_device_ & (int)LOG_DEVICE::DEVICE_CONSL) {
            LoggerConslPrintter::getInstance().print(item);
        }
        if (log_device_ & (int)LOG_DEVICE::DEVICE_FILE) {
            LoggerFilePrinter::getInstance().print(item);
        }
        if (log_device_ & (int)LOG_DEVICE::DEVICE_CUST) {
            LoggerCustPrinterMgr::getInstance().print(item);
        }
    }
}

void LoggerPrintMgr::postLog(const LogItem& logger) {
    if (logger.property_.level_ & level_) {
        if (open_log_que_) {
            std::lock_guard<std::mutex> lock(mtx_);
            logger_que_.push_back(std::move(logger));
            cv_.notify_one();
        }
        else {
            auto logger_temp = std::move(logger);
            if (log_device_ & (int)LOG_DEVICE::DEVICE_CONSL) {
                LoggerConslPrintter::getInstance().print(logger_temp);
            }
            if (log_device_ & (int)LOG_DEVICE::DEVICE_FILE) {
                LoggerFilePrinter::getInstance().print(logger_temp);
            }
            if (log_device_ & (int)LOG_DEVICE::DEVICE_CUST) {
                LoggerCustPrinterMgr::getInstance().print(logger_temp);
            }
        }

    }
}
